package com.explorati.LeetCode024.swapPairs;

/**
 * @ Author : Weijian_Wang
 * @ Date : Created in 20:47 2020/10/13 0013
 * @ Description ：
 */
public class Solution {
    public static class ListNode {
      int val;
      ListNode next;
      ListNode() {}
      ListNode(int val) { this.val = val; }
      ListNode(int val, ListNode next) { this.val = val; this.next = next; }
  }

    public ListNode swapPairs(ListNode head) {
        //如果当前节点为空或者当前节点下一个节点为空，返回当前节点
        if(head == null || head.next == null) {
            return head;
        }
        //递归解法
        //新的头结点为当前节点的下一个节点
        //当前头结点的下一个节点为 当前头结点的下一个节点的下一个节点
        //新的头结点的下一个节点为原先的头结点
        ListNode newHead = head.next;
        head.next = swapPairs(newHead.next);
        newHead.next = head;

        return newHead;
    }

    public static void main(String[] args) {
        ListNode head = new ListNode(1);
        head.next = new ListNode(2);
        head.next.next = new ListNode(3);
        head.next.next.next = new ListNode(4);

        new Solution().swapPairs(head);
    }
}
